import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    // List<Message> messageList = new ArrayList<>();

    // 客户端 提交请求 给服务器
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 将 json 形式的数据读取出来
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        // 添加到内存中
        // messageList.add(message);

        // 优化: 通过 Mysql 进行存储
        save(message);

        // 设置格式
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write("{  \"ok\": 1  }");
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        // 将数据重新以 json 的字符串形式 发送给客户端
        List<Message> messageList = null;
        messageList = load();
        String respString = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respString);
    }


    private void save(Message message) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            // 存储
            // 先构造 sql 语句
            String sql = "insert into MessageWall values(?, ?, ?)";
            // 先放进入, 等待处理
            statement = connection.prepareStatement(sql);
            statement.setString(1, message.from);
            statement.setString(2, message.to);
            statement.setString(3, message.message);
            // 真正执行 sql 语句, 会返回受影响的行数
            int state = statement.executeUpdate();
            if (state == 1) {
                System.out.println("添加成功");
            } else {
                System.out.println("添加失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, null);
        }
    }

    private List<Message> load() {
        // 加载数据中的数据
        List<Message> messageList = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            // 构造 sql 语句
            String sql = "select * from MessageWall";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messageList.add(message);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }

        return messageList;
    }
}
